package cn.seaboot.commons.http.call;

import cn.seaboot.commons.http.HttpStatusException;
import org.apache.hc.core5.http.ClassicHttpResponse;
import org.apache.hc.core5.http.HttpException;
import org.apache.hc.core5.http.HttpStatus;
import org.apache.hc.core5.http.io.HttpClientResponseHandler;
import org.apache.hc.core5.http.io.entity.EntityUtils;

import java.io.IOException;

/**
 * 将后台数据响应读取成字符串
 *
 * @author Mr.css
 * @version 2025-02-14 9:59
 */
public class TextHandler implements HttpClientResponseHandler<String> {

    private final String charset;

    public TextHandler(String charset) {
        this.charset = charset;
    }

    @Override
    public String handleResponse(ClassicHttpResponse response) throws HttpException, IOException {
        int code = response.getCode();
        if (code != HttpStatus.SC_OK) {
            throw new HttpStatusException("Error status :" + code);
        }
        return EntityUtils.toString(response.getEntity(), this.charset);
    }
}
